package com.atguigu.tingshu.user.service.impl;
import java.math.BigDecimal;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.LastUserListenPlayVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;

import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	RedisTemplate redisTemplate;
	@Autowired
	KafkaService kafkaService;

	@Override
	public void updateListenProcess(Long userId, UserListenProcessVo userListenProcessVo) {

		// 构建查询条件对象
		Criteria criteria = Criteria.where("trackId").is(userListenProcessVo.getTrackId());
		Query query = Query.query(criteria);
		//获取Mongodb中集合名称
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);

		UserListenProcess listenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		//判断此声音是否存在
		if (listenProcess!=null){
			//此声音存在，修改时间和进度
			listenProcess.setUpdateTime(new Date());
			listenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			mongoTemplate.save(listenProcess, collectionName);
		}else {
			// 创建声音进度存储对象，并将其存储到Mongodb中
			UserListenProcess userListenProcess = new UserListenProcess();
			BeanUtils.copyProperties(userListenProcessVo, userListenProcess);
			userListenProcess.setId(ObjectId.get().toString());
			userListenProcess.setUserId(userId);
			userListenProcess.setIsShow(1);
			userListenProcess.setCreateTime(new Date());
			userListenProcess.setUpdateTime(new Date());
			//获取Mongodb中集合名称
			String newcollectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
			mongoTemplate.save(userListenProcess, newcollectionName);
		}
		// 构建Redis的key
		Date date = new Date() ;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd") ;
		String dateFormat = simpleDateFormat.format(date);
		String redisKey = "track:play:" + userListenProcessVo.getTrackId() + ":" + dateFormat + ":" + userId ;
		Boolean hasKey = redisTemplate.hasKey(redisKey);
		if (!hasKey){//Redis中不存在对应的key
			//用Kafka发送增加播放量的请求
			TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
			trackStatMqVo.setBusinessNo(UUID.randomUUID().toString().replace("-",""));
			trackStatMqVo.setAlbumId(userListenProcessVo.getAlbumId());
			trackStatMqVo.setTrackId(userListenProcessVo.getTrackId());
			trackStatMqVo.setStatType(SystemConstant.ALBUM_STAT_PLAY);
			trackStatMqVo.setCount(1);

			kafkaService.sendMessage(KafkaConstant.QUEUE_TRACK_STAT_UPDATE , JSON.toJSONString(trackStatMqVo) );


			//向Redis中添加key
			redisTemplate.opsForValue().set(redisKey,"1",1, TimeUnit.DAYS);
		}
	}

	@Override
	public BigDecimal getTrackBreakSecond(Long trackId) {
		//获取用户id
		Long userId = AuthContextHolder.getUserId();
		//获取查询条件-根据用户id和声音id
		Criteria criteria = Criteria.where("userId").is(userId).and("trackId").is(trackId);
		Query query = Query.query(criteria);
		//获取Mongodb中集合名称
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		UserListenProcess mongoTemplateOne = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		//判断是否有播放记录
		if(mongoTemplateOne!=null){
			//返回播放时间
			return mongoTemplateOne.getBreakSecond();
		}
		return new BigDecimal(0);
	}

	@Override
	public LastUserListenPlayVo getLatelyTrack() {
		//获取用户最后一次声音的播放进度
		//获取用户id
		Long userId = AuthContextHolder.getUserId();
		//获取集合名称
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		Criteria criteria = Criteria.where("userId").is(userId);
		Query query = Query.query(criteria);
		query.limit(1);
		//根据修改时间降序排列
		query.with(Sort.by(Sort.Direction.DESC,"updateTime"));

		//查询最后一次声音的播放进度
		UserListenProcess mongoTemplateOne = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		//构建响应数据
		LastUserListenPlayVo lastUserListenPlayVo = new LastUserListenPlayVo();
		if (mongoTemplateOne!=null){
			lastUserListenPlayVo.setAlbumId(mongoTemplateOne.getAlbumId());
			lastUserListenPlayVo.setTrackId(mongoTemplateOne.getTrackId());
		}
		return lastUserListenPlayVo;
	}
}
